import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { SystemStatus, LoginCredentials, QueryRequest } from '@/types'
import { api } from '@/api'

export const useSystemStore = defineStore('system', () => {
  // 状态
  const systemStatus = ref<SystemStatus>({
    app_initialized: false,
    agent_ready: false,
    session_active: false,
    api_key_configured: false,
    server_info: {
      environment: 'unknown',
      python_version: '',
      fastapi_version: ''
    }
  })

  const isAuthenticated = computed(() => systemStatus.value.session_active)
  const isSystemReady = computed(() =>
    systemStatus.value.app_initialized && systemStatus.value.agent_ready
  )

  // 操作
  const fetchSystemStatus = async (): Promise<SystemStatus> => {
    try {
      const response = await api.get('/status')
      systemStatus.value = response.data
      return response.data
    } catch (error) {
      console.error('获取系统状态失败:', error)
      throw error
    }
  }

  const login = async (credentials: LoginCredentials) => {
    try {
      const response = await api.post('/auth/login', credentials)
      if (response.data.success) {
        // 登录成功，更新系统状态
        await fetchSystemStatus()
      }
      return response.data
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    }
  }

  const queryClassroom = async (request: QueryRequest) => {
    try {
      const response = await api.post('/chat/query', request)
      return response.data
    } catch (error) {
      console.error('查询失败:', error)
      throw error
    }
  }

  const healthCheck = async () => {
    try {
      const response = await api.get('/health')
      return response.data
    } catch (error) {
      console.error('健康检查失败:', error)
      throw error
    }
  }

  return {
    // 状态
    systemStatus,

    // 计算属性
    isAuthenticated,
    isSystemReady,

    // 操作
    fetchSystemStatus,
    login,
    queryClassroom,
    healthCheck
  }
})